<?php

class  UserGoldCoinLog extends BaseModel
{
    public $res;
    public $expire;

    public function getSource()
    {
        return "f_user_gold_coin_log";
    }

    public function page_list($params)
    {
        $page = isset($params['page']) ? $params['page'] : 1;
        $size = 10;
        if ($page > 0) {
            $page = ($page - 1) * $size;
        }
        $condition = '1=1 ';

        if (isset($params['phone']) && !empty($params['phone'])) {
            $userDb = new User();
            $info   = $userDb->findFirstByPhone($params['phone']);
            if (!$info) {
                return [];
            }
            $condition .= " and user_id = $info->id";
        }
        if (isset($params['start_time']) && !empty($params['start_time'])) {
            $condition .= " and created_at >= '{$params['start_time']}'";
        }

        if (isset($params['user_id']) && !empty($params['user_id'])) {
            $condition .= " and user_id = {$params['user_id']}";
        }

        if (isset($params['end_time']) && !empty($params['end_time'])) {
            $condition .= " and created_at <= '{$params['end_time']}'";
        }

        $result['total'] = $this::count($condition);
        $result['list']  = $this::find(
            array(
                $condition,
                "order"  => 'id desc',
                'limit'  => $size,
                'offset' => $page
            ))->toarray();
        return $result;
    }

    public function initialize()
    {
        parent::initialize();
        $this->res['res'] = false;
        $this->expire     = 60 * 60 * 20;
    }

    /**
     * 添加钻石日志
     * @param $params
     * @return bool
     */
    public function add_log($params)
    {
        if ($this->save($params)) {
            return true;
        }
        return false;
    }

    /**
     * @param $user_id
     * @param $pageSize
     * @param int $page
     */
    public function get_page($user_id, $page, $pageSize)
    {
        $condition = " user_id = $user_id";
        $user_list = $this::find(
            array(
                $condition,
                "order"  => 'id desc',
                "limit"  => $pageSize,
                "offset" => ($page - 1) * $pageSize,
            )
        );
        if ($user_list) {
            $res = array();
            foreach ($user_list->toarray() as $val) {
                $remarks = explode(':', $val['remarks']);
                if ($remarks[0]) {
                    $val['remarks'] = $remarks[0];
                } else {
                    continue;
                }
                if (isset($remarks[1])) {
                    $val['num'] = $remarks[1];
                }
                $res[] = $val;
            }
            return $res;
        } else {
            return array();
        }
    }

    //每日分佣钻石统计
    public function day_gold_commission($user_id, $gold, $type = 10)
    {
        $start_end_time          = CommonController::timeChange(1);  //上月的
        $condition['conditions'] = "user_id = $user_id and type = $type and created_at >= '{$start_end_time['start_at']}' and created_at <= '{$start_end_time['end_at']}'  ";
        $data                    = $this->findFirst($condition);
        if ($data) {
            $remarks       = explode(':', $data->remarks);
            $remarks[1]    += $gold;
            $data->remarks = $remarks[0] . ':' . $remarks[1];
        } else {
            $data          = new $this();
            $data->user_id = $user_id;
            $remark        = '';
            switch ($type) {
                case 10:
                    $remark = "下级视频广告分佣:$gold";
                    break;
                case 15:
                    $remark = "下级玩游戏分佣:$gold";
                    break;
                case 17:
                    $remark = "下级摇一摇钻石分佣:$gold";
                    break;
            }
            $data->type       = $type;
            $data->remarks    = $remark;
            $data->created_at = date('Y-m-d H:i:s');
        }
        $data->save();
        return true;
    }

    //批量添加
    public function batch_insert(array $data)
    {
        if (count($data) == 0) {
            throw new \Exception('参数错误');
        }
        $keys = array_keys(reset($data));
        $keys = array_map(function ($key) {
            return "`{$key}`";
        }, $keys);
        $keys = implode(',', $keys);
        $sql  = "INSERT INTO " . $this->getSource() . " ({$keys}) VALUES ";
        foreach ($data as $v) {
            $v      = array_map(function ($value) {
                return "'{$value}'";
            }, $v);
            $values = implode(',', array_values($v));
            $sql    .= " ({$values}), ";
        }
        $sql = rtrim(trim($sql), ',');
        //DI中注册的数据库服务名称为"db"
        $result = $this->getDI()->get('db')->execute($sql);

        if (!$result) {
            return false;
        }
        return $result;
    }


    //每日自己分钻石日志
    public function self_day_gold_log($user_id, $gold, $type = 10)
    {
        $start_end_time          = CommonController::timeChange(1);  //今天
        $condition['conditions'] = "user_id = $user_id and type = $type and created_at >= '{$start_end_time['start_at']}' and created_at <= '{$start_end_time['end_at']}'  ";
        $data                    = $this->findFirst($condition);
        if ($data) {
            $remarks       = explode(':', $data->remarks);
            $remarks[1]    += $gold;
            $data->remarks = $remarks[0] . ':' . $remarks[1];
        } else {
            $data             = new $this();
            $data->user_id    = $user_id;
            $data->type       = $type;
            $data->remarks    = "摇一摇钻石:$gold";
            $data->created_at = date('Y-m-d H:i:s');
        }
        $data->save();
        return true;
    }

//    public function sumNum(){
//        $columns['conditions'] = 'status = 1';
//        $columns['column'] = 'num';
//        return $this::sum($columns);
//    }

    public function sumNum($status = 1, $uid = 0, $type = 0)
    {
        $columns['conditions'] = 'status = ' . $status;
        if ($uid > 0) {
            $columns['conditions'] .= ' and user_id = ' . $uid;
        }
        if ($type > 0) {
            $columns['conditions'] .= ' and type = ' . $type;
        }
        $columns['column'] = 'num';
        return $this::sum($columns);
    }
}
